package com.smart.reflect;

import com.smart.Car;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * @author chenxingyu
 * @date 2019/8/20 19:36
 */
public class ReflectTest {
    public static Car initByDefaultConst() throws Throwable {
        //①通过在类装载器获取Car类对象
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class clazz = loader.loadClass("com.smart.reflect.Car");

        //②获取类的默认构造器并通过它实例化
        Constructor cons = clazz.getDeclaredConstructor((Class[]) null);
        Car car = (Car) cons.newInstance();

        //③通过反射的方法设置属性
        Method setBrand = clazz.getMethod("setBrand", String.class);
        setBrand.invoke(car, "传祺CS4");
        Method setColor = clazz.getMethod("setColor", String.class);
        setColor.invoke(car, "白色");
        Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
        setMaxSpeed.invoke(car, 200);
        return car;
    }

    public static void main(String[] args) throws Throwable {
        Car car = initByDefaultConst();
        car.introduce();
        //结果：brand:传祺CS4;color:白色;maxSpeed:200
    }
}
